import { getRequest } from "@/api/request";
import { AxiosResponse } from "axios";
const REQUEST_URL = {
  lyric: "/lyric",
};

export interface INlyricList {
  time: number | string | undefined;
  lyric: string;
}

const handleTime = (time: string) => {
  if (!time) {
    return "";
  }
  const pattern = /(\d{2}):(\d{2}.\d{2,3})/;
  const matchResult = time.match(pattern);

  if (matchResult) {
    const [, minute, second] = matchResult;
    return Number(minute) * 60 + Number(second);
  }
};

const handleLyric = (lyric: string) => {
  const newlyric: Array<INlyricList> = [];
  lyric.split(/[\n]/).forEach((it) => {
    const content = it.split(/\[(.+?)\]/);
    const time = handleTime(content[1]); // 将时分秒 全部转化成和audio的当前时间相同格式的数据
    const lyric = content[2];
    newlyric.push({
      time: time,
      lyric: lyric,
    });
  });
  return newlyric.filter((it) => it["lyric"]);
};

const filter = (res: AxiosResponse) => {
  return {
    lyricList: handleLyric(res.data.lrc.lyric),
  };
};

export const getlyric = (id: number | string | undefined) => {
  return getRequest(REQUEST_URL.lyric + `?id=${id}`).then(filter);
};
